package com.sw.chinesewriteboard.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sw.chinesewriteboard.databinding.ItemGeziBinding;

import java.util.List;

/**
 * @Description:
 * @author: GordenGao
 * @Email: gordengao124@gmail.com
 * @date: 2021年06月21日 21:27
 */
public class GeziAdapter extends RecyclerView.Adapter<GeziAdapter.ZitiViewHolder> {

    private ItemClickListener mListener;
    private List<Integer> mGeziList;

    private int curIndex = 0;
    private int preIndex = 0;

    public GeziAdapter(List<Integer> geziList, ItemClickListener listener) {
        this.mListener = listener;
        this.mGeziList = geziList;
    }

    @NonNull
    @Override
    public ZitiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemGeziBinding binding = ItemGeziBinding.inflate(LayoutInflater.from(parent.getContext()));
        return new ZitiViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ZitiViewHolder holder, final int position) {
        holder.btn.setBackgroundResource(mGeziList.get(position));
        if (position == curIndex) {
            holder.bg.setVisibility(View.VISIBLE);
        } else {
            holder.bg.setVisibility(View.GONE);
        }
        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onItemClick(mGeziList.get(position));
                preIndex = curIndex;
                curIndex = position;
                notifyItemChanged(preIndex);
                notifyItemChanged(curIndex);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mGeziList.size();
    }

    public static class ZitiViewHolder extends RecyclerView.ViewHolder {
        ImageView btn;
        ImageView bg;

        public ZitiViewHolder(@NonNull ItemGeziBinding binding) {
            super(binding.getRoot());
            btn = binding.geziBtn;
            bg = binding.geziBg;
        }
    }

    public interface ItemClickListener {
        void onItemClick(@DrawableRes int drwId);
    }
}
